#include "urdfparser.h"
#include "meshloader.h"
#include <QDebug>

MeshLoader::MeshLoader(UrdfParser* parser, QObject *parent)
    : QThread(parent)
    , m_parser(parser)
    , m_isRunning(false)
{
}

MeshLoader::~MeshLoader()
{
    // 请求线程停止
    requestInterruption();
    quit();
    wait();
}

void MeshLoader::run()
{
    if (!m_parser) {
        emit loadFinished(false);
        return;
    }

    m_isRunning = true;
    const QVector<Link>& links = m_parser->getLinks();
    int totalLinks = links.size();
    int currentLink = 0;

    for (const Link& link : links) {
        if (isInterruptionRequested()) {
            m_isRunning = false;
            emit loadFinished(false);
            return;
        }

        if (!link.mesh_path.isEmpty()) {
            Mesh mesh;
            if (mesh.loadFromFile(link.mesh_path)) {
                MeshLoadData data;
                data.linkName = link.name;
                data.vertices = mesh.vertices;
                data.indices = mesh.indices;
                data.needsInit = true;
                
                emit meshLoaded(data);
                emit progressUpdated((currentLink * 100) / totalLinks);
            }
        }
        currentLink++;
    }
    
    m_isRunning = false;
    emit loadFinished(true);
}
